<template>
  <div style="padding: 20px">
    <!-- 打开上传弹窗按钮 -->
    <el-button type="primary" @click="openUploadDialog">上传</el-button>

    <!-- 文件列表 -->
    <el-table :data="state.records" style="width: 100%">
      <el-table-column prop="filename" label="文件名" />
      <el-table-column prop="versionnum" label="版本号" />
      <el-table-column prop="filesize" label="文件大小">
        <template #default="scope">
          {{
            scope.row.filesize
              ? scope.row.filesize >= 1024 * 1024
                ? (scope.row.filesize / (1024 * 1024)).toFixed(2) + " MB"
                : scope.row.filesize >= 1024
                ? (scope.row.filesize / 1024).toFixed(2) + " KB"
                : scope.row.filesize + " B"
              : "-"
          }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="文件描述" />
      <el-table-column prop="devicetype" label="设备类型">
        <template #default="scope">
          {{ scope.row.devicetype === "ic" ? "集成设备" : "功率设备" }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-space>
            <el-button type="text" @click="downloadFile(scope.row)"
              >下载</el-button
            >
            <el-button type="text" @click="deleteFile(scope.row)"
              >删除</el-button
            >
            <el-button type="text" @click="upgradeDialog(scope.row)"
              >升级</el-button
            >
          </el-space>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      :current-page="state.currentPage"
      :page-sizes="[10, 20, 30]"
      :page-size="state.pageSize"
      style=""
      layout="total, sizes, prev, pager, next, jumper"
      :total="state.total"
    />
    <el-dialog
      v-model="dialogVisible"
      title="文件上传"
      width="50%"
      destroy-on-close
    >
      <el-form
        :model="uploadForm"
        :rules="rules"
        ref="uploadFormRef"
        label-width="120px"
      >
        <el-form-item label="设备类型" prop="devicetype">
          <el-select
            v-model="uploadForm.devicetype"
            @change="changeDevicetype"
            style="width: 200px"
            placeholder="请选择设备类型"
          >
            <!-- 假设设备类型，可根据实际情况修改 -->
            <el-option label="集成设备" value="ic" />
            <el-option label="功率设备" value="pd" />
          </el-select>
        </el-form-item>
        <el-form-item label="文件">
          <el-upload
            class="upload-demo"
            action="#"
            ref="uploadInstance"
            accept=".zip"
            :limit="1"
            style="width: 100%"
            :multiple="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            :on-remove="handleRemoveFile"
            :auto-upload="false"
          >
            <el-button type="primary" v-if="fileList.length == 0"
              >选择文件</el-button
            >
          </el-upload>
        </el-form-item>
        <el-form-item label="文件版本" prop="version">
          <el-input-number
            v-model="uploadForm.version"
            :min="1"
            placeholder="请输入文件版本号"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="指定设备" prop="devicetopic">
          <el-select
            v-model="uploadForm.devicetopic"
            style="width: 400px"
            clearable
            placeholder="请选择设备,默认升级所有该类型设备"
          >
            <el-option
              v-for="(item, index) in curentTypeDevices"
              :key="index"
              :label="item.name"
              :value="item.topic"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文件描述" prop="remark">
          <el-input
            v-model="uploadForm.remark"
            :rows="2"
            type="textarea"
            placeholder="请输入文件描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="success" @click="submitFiles">提交文件</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="upgradeDialogVisible"
      title="选择升级设备"
      width="400px"
    >
      <el-select
        v-model="selectedDeviceTopic"
        placeholder="请选择设备,默认升级所有该类型设备"
        clearable
      >
        <el-option
          v-for="device in curentTypeDevices"
          :key="device.id"
          :label="device.name"
          :value="device.topic"
        />
      </el-select>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="upgradeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="upgradeFile">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getClientSystemFilePage,
  deleteClientSystemFile,
  upgradeClientSystemFile,
} from "@/api/device/clientapp";
import { devicelist } from "@/api/system/device.js";
import {
  uploadAppFilesApi,
  downloadAppFilesApi,
} from "@/api/device/fileUtilApi";
import { download } from "@/utils/request";
const dialogVisible = ref(false);
// 存储文件列表
const fileList = ref([]);
const devicelists = ref([]);
const curentTypeDevices = ref([]);
const upgradeDialogVisible = ref(false);
const selectedDeviceTopic = ref("");
const currentFile = ref({});
// 打开上传弹窗的函数
const openUploadDialog = () => {
  if (uploadFormRef.value) {
    uploadFormRef.value.resetFields();
  }
  if (uploadInstance.value) {
    uploadInstance.value.clearFiles();
  }
  fileList.value = [];
  uploadForm.devicetype = "ic"; // 重置时设置默认设备类型为 ic
  uploadForm.devicetopic = "";
  curentTypeDevices.value = devicelists.value.filter(
    (item) => item.type == uploadForm.devicetype
  );
  dialogVisible.value = true;
};

// 升级文件方法
const upgradeDialog = (row) => {
  currentFile.value = row;
  curentTypeDevices.value = devicelists.value.filter(
    (item) => item.type == row.devicetype
  );
  selectedDeviceTopic.value = "";
  upgradeDialogVisible.value = true;
};
const changeDevicetype = (val) => {
  curentTypeDevices.value = devicelist.value.filter(
    (item) => item.devicetype == val
  );
};

const state = reactive({
  records: [],
  total: 0,
  currentPage: 1,
  pageSize: 10,
});
const deleteFile = (row) => {
  ElMessageBox.confirm("是否删除该文件？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // 调用删除 API
    deleteClientSystemFile(row.id).then(() => {
      ElMessage.success("文件删除成功");
      // 重新获取分页数据
      getFileList();
    });
  });
};
// 上传表单数据
const uploadForm = reactive({
  remark: "",
  version: 1,
  fileList: [],
  devicetype: "ic",
  devicetopic: "",
});
// 表单引用
const uploadFormRef = ref(null);
const uploadInstance = ref(null);

// 表单校验规则
const rules = {
  version: [{ required: true, message: "请输入文件版本号", trigger: "blur" }],
  devicetype: [
    { required: true, message: "请选择设备类型", trigger: "change" },
  ],
};

// 文件变化处理
const handleFileChange = (file) => {
  // 若文件不存在，使用用户输入的版本号和设备类型
  fileList.value = [
    {
      name: file.name,
      size: (file.size / 1024).toFixed(2) + " KB",
      file: file.raw,
    },
  ];
};

// 上传前校验
const beforeUpload = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage.error("上传文件大小不能超过 10MB!");
  }
  return isLt10M;
};

// 下载文件
const downloadFile = (row) => {
  window.open("/api/download/" + row.filepath, "_blank", "noopener,noreferrer");
};

// 提交文件
const submitFiles = async () => {
  if (!uploadFormRef.value) return;
  await uploadFormRef.value.validate((valid) => {
    if (valid) {
      if (fileList.value.length === 0) {
        ElMessage.warning("请先添加要上传的文件");
        return;
      }

      try {
        const formData = new FormData();
        fileList.value.forEach((fileInfo) => {
          formData.append("file", fileInfo.file);
          formData.append(`remark`, uploadForm.remark);
          formData.append(`versionnum`, uploadForm.version);
          formData.append(`devicetype`, uploadForm.devicetype);
          formData.append("devicetopic", uploadForm.devicetopic);
        });

        // 调用上传 API
        uploadAppFilesApi(formData)
          .then(() => {
            ElMessage.success("文件提交成功");
            // 清空文件列表
            fileList.value = [];
            // 重新获取分页数据
            getFileList();
            // 关闭弹窗
            dialogVisible.value = false;
          })
          .catch((error) => {
            ElMessage.error("文件提交失败，请重试");
            console.error("文件提交失败:", error);
          });
      } catch (error) {
        ElMessage.error("文件提交失败，请重试");
        console.error("文件提交失败:", error);
      }
    } else {
      ElMessage.error("请填写必填项");
      return false;
    }
  });
};

// 获取分页文件列表
const getFileList = async () => {
  const params = {
    page: state.currentPage,
    pageSize: state.pageSize,
  };
  getClientSystemFilePage(params).then((res) => {
    state.records = res.records;
    state.total = res.total;
  });
};

// 页码改变时触发
const handleCurrentChange = (val) => {
  state.currentPage = val;
  getFileList();
};

// 每页显示数量改变时触发
const handleSizeChange = (val) => {
  state.pageSize = val;
  getFileList();
};

// 升级文件函数，你可以根据实际需求实现具体逻辑
const upgradeFile = () => {
  ElMessageBox.confirm("是否升级设备系统？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // 调用删除 API
    upgradeClientSystemFile(currentFile.value.id, {
      devicetopic: selectedDeviceTopic.value,
    }).then(() => {
      ElMessage.success("升级指令已发送");
      upgradeDialogVisible.value = false;
      // 重新获取分页数据
      // getFileList();
    });
  });
};

// 组件挂载时获取文件列表
onMounted(() => {
  getFileList();

  devicelist({}).then((res) => {
    devicelists.value = res;
  });
});
</script>

<style scoped>
.upload-demo {
  margin-bottom: 20px;
}
</style>
